package service

import (
	"delivery-server/utils/response"
	"github.com/go-xorm/xorm"
	"strconv"
)

type VoucherService interface {

	// UseVoucher 使用金券
	UseVoucher(userId, voucherId int, voucherCode string) (code int)
}

func NewVoucherService(engine *xorm.Engine) VoucherService {
	return &voucherService{
		Engine: engine,
	}
}

type voucherService struct {
	Engine *xorm.Engine
}

// UseVoucher 使用金券
func (vs voucherService) UseVoucher(userId, voucherId int, voucherCode string) (code int) {
	
	session := vs.Engine.NewSession()
	defer session.Close()

	// 开始事务
	err := session.Begin()
	if err != nil {
		return response.ServerErrCode
	}

	sqlStr := "SELECT amount FROM voucher WHERE id = ? AND code = ? AND user_id IS NULL"
	results, err := vs.Engine.QueryString(sqlStr, voucherId, voucherCode)

	if err != nil  {
		code = response.ServerErrCode
		_ = session.Rollback()
		return
	}

	// 兑换码错误
	if len(results) == 0 {
		code = response.DataErrCode
		_ = session.Rollback()
		return
	}

	sqlStr = "UPDATE voucher SET user_id = ? WHERE id = ?"
	_, err = vs.Engine.Exec(sqlStr, userId, voucherId)

	if err != nil {
		code = response.ServerErrCode
		_ = session.Rollback()
		return
	}

	amountStr := results[0]["amount"]
	amount, err := strconv.Atoi(amountStr)
	if err != nil {
		_ = session.Rollback()
		return response.ServerErrCode
	}

	sqlStr = "UPDATE user SET balance = balance + ? WHERE id = ?"
	_, err = vs.Engine.Exec(sqlStr, amount, userId)
	if err != nil {
		_ = session.Rollback()
		return response.ServerErrCode
	}

	// 结束事务
	err = session.Commit()
	if err != nil {
		return response.ServerErrCode
	}

	return response.SuccessCode
}